<template>
    <div>
        <div style="margin-top: 10px;display: flex;justify-content:space-between;">
            <div>
                <el-input v-model="keywords"
                          size="small"
                          placeholder="请输入用户名..."
                          prefix-icon="el-icon-search"
                          @keydown.enter.native = "search"
                          style="width: 450px;margin-right: 8px"></el-input>
                <el-button icon="el-icon-search" type="primary" @click="search" size="small">搜索</el-button>
            </div>
            <el-button icon="el-icon-circle-plus-outline" type="primary" @click="showAddView" size="small">新增账户</el-button>
        </div>
        <div class="hrcenter">
            <el-card class="box-card hrcard" v-for="(hr,index) in hrs" :key="index">
                <div slot="header" class="clearfix">
                    <span>{{hr.name}}</span>
                    <el-button style="float: right; padding: 3px 0;color: red" type="text" icon="el-icon-delete" @click="deleteHr(hr)">删除</el-button>
                </div>
                <div>
                    <div class="imgposition">
                        <img :src="hr.userface" :alt="hr.name" :title="hr.name" class="userface">
                    </div>
                    <div class="userinfo">
                        <div><i class="el-icon-s-custom"></i>&nbsp; :&nbsp; {{hr.name}}</div>
                        <div><i class="el-icon-s-marketing"></i>&nbsp; :&nbsp; {{hr.department.name}}</div>
                        <div><i class="el-icon-phone"></i>&nbsp; :&nbsp; {{hr.phone}}</div>
                        <div><i class="el-icon-message"></i>&nbsp; :&nbsp; {{hr.email}} </div>
                        <div><i class="el-icon-s-home"></i>&nbsp; :&nbsp; {{hr.address}}</div>
                        <div>
                            用户状态:
                            <el-switch
                                    v-model="hr.enabled"
                                    active-text="启用"
                                    inactive-text="禁用"
                                    @change="enabledChange(hr)"
                                    active-color="#13ce66"
                                    inactive-color="#ff4949">
                            </el-switch>
                        </div>
                        <div class="hrrole">
                            <i class="el-icon-user-solid"></i>:
                            <el-tag size="mini" effect="dark" type="success" v-for="(role,indexj) in hr.roles" :key="indexj">{{role.nameZh}}</el-tag>
                            <el-popover
                                    placement="right"
                                    title="角色列表"
                                    width="200"
                                    @show="showPop(hr)"
                                    @hide="hidePop(hr)"
                                    trigger="click">
                                <el-select v-model="selectroles" placeholder="请选择" multiple>
                                    <el-option
                                            v-for="(r,indexk) in allroles"
                                            :key="indexk"
                                            :label="r.nameZh"
                                            :value="r.id">
                                    </el-option>
                                </el-select>
                                <el-button icon="el-icon-more" size="mini" type="text" slot="reference"></el-button>
                            </el-popover>

                        </div>
                        <div>备注:{{hr.remark}}</div>
                    </div>
                </div>
            </el-card>
        </div>
        <el-dialog
                title="新增系统用户"
                :visible.sync="dialogVisible"
                width="30%"
                top="2vh"
                center
                @close="handleClose">
            <div>
                <el-form :model="hr" :rules="hrrules" ref="hrForm" label-width="100px">
                    <el-form-item label="用户名:" prop="username">
                        <el-input size="mini"
                                  style="width: 280px"
                                  prefix-icon="el-icon-message"
                                  v-model="hr.username" placeholder="请输入用户名..."></el-input>
                    </el-form-item>
                    <el-form-item label="工号:" prop="jobNo">
                        <el-autocomplete
                                prefix-icon="el-icon-message"
                                style="width: 280px"
                                class="inline-input"
                                v-model="hr.jobNo"
                                :fetch-suggestions="querySearch"
                                placeholder="请输入工号"
                                :trigger-on-focus="false"
                                @select="handleSelect"
                                size="mini"
                        ></el-autocomplete>
                    </el-form-item>
                    <el-form-item label="部门名称:" prop="depName">
                        <el-input size="mini"
                                  style="width: 280px"
                                  prefix-icon="el-icon-message"
                                  readonly="readonly"
                                  v-model="hr.department.name" placeholder="输入工号后自动带出..."></el-input>
                    </el-form-item>
                    <el-form-item label="员工姓名:" prop="name">
                        <el-input size="mini"
                                  style="width: 280px"
                                  prefix-icon="el-icon-message"
                                  readonly="readonly"
                                  v-model="hr.name" placeholder="输入工号后自动带出..."></el-input>
                    </el-form-item>
                    <el-form-item label="电子邮箱:" prop="email">
                        <el-input size="mini" style="width: 280px" prefix-icon="el-icon-message"
                                  v-model="hr.email" placeholder="输入工号后自动带出..."></el-input>
                    </el-form-item>
                    <el-form-item label="手机号码:" prop="phone">
                        <el-input size="mini" style="width: 280px" prefix-icon="el-icon-message"
                                  v-model="hr.phone" placeholder="输入工号后自动带出..."></el-input>
                    </el-form-item>
                    <el-form-item label="座机号码:" prop="telephone">
                        <el-input size="mini" style="width: 280px" prefix-icon="el-icon-message"
                                  v-model="hr.telephone" placeholder="请输入座机号码..."></el-input>
                    </el-form-item>
                    <el-form-item label="密码:" prop="password">
                        <el-input type="password"
                                  size="mini"
                                  style="width: 280px"
                                  prefix-icon="el-icon-message"
                                  v-model="hr.password"
                                  autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="确认密码" prop="checkPass">
                        <el-input
                                type="password"
                                size="mini"
                                style="width: 280px"
                                prefix-icon="el-icon-message"
                                v-model="hr.checkPass"
                                autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
            </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false" size="small">取 消</el-button>
            <el-button type="primary" @click="addHr" size="small">确 定</el-button>
        </span>
        </el-dialog>
    </div>
</template>

<script>
    import {checkphone} from "../../utils/myvalid";

    export default {
        name: "SysHr",
        data(){
            var validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.hr.password) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            return{
                keywords:'',
                hrs:[],
                allroles:[],
                selectroles:[],
                dialogVisible:false,
                hr:{
                    jobNo:null,
                    department:{
                        id:null,
                        name:''
                    },
                    name:null,
                    phone:null,
                    telephone:null,
                    email:null,
                    address:null,
                    username:null,
                    password:null,
                    checkPass:null,
                    enabled:1,
                    remark:null
                },
                hrrules: {
                    username: [{required: true, message: '用户名不可以为空', trigger: 'blur'}],
                    jobNo: [{required: true, message: '员工工号不可以为空', trigger: 'blur'}],
                    name: [{required: true, message: '员工名称不可以为空', trigger: 'blur'}],
                    phone: [
                        {required: true, validator: checkphone, trigger: 'blur'}],
                    email: [
                        {required: true, message: '电子邮箱不可以为空', trigger: 'blur'},
                        {type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur'}
                    ],
                    address: [{required: true, message: '联系地址不可以为空', trigger: 'blur'}],
                    password: [{required: true, message: '密码不可以为空', trigger: 'blur'}],
                    checkPass: [
                        { required: true,validator: validatePass2, trigger: 'blur' }
                    ],
                },
                empjobNos:[]
            }
        },
        mounted() {
            this.getHrs();
        },
        methods:{
            addHr(){
                this.$refs.hrForm.validate(valid => {
                    if (valid) {
                        this.postRequest("/system/hr/", this.hr).then(resp => {
                            if (resp) {
                                this.dialogVisible = false;
                                this.getHrs();
                            }
                        })
                    }
                })
            },
            //Input框输入时进行后端接口请求，把结果集放到搜索建议中
            querySearch(queryString, cb) {
                this.empjobNos = [];
                this.getRequest("/personnel/ec/"+queryString).then(resp=>{
                    for (let item of resp) {
                        this.empjobNos.push({"value": item.jobNo})
                    }
                    var empjobNos = this.empjobNos;
                    var results = queryString ? empjobNos.filter(this.createFilter(queryString)) : empjobNos;
                    // 调用 callback 返回建议列表的数据
                    cb(results);
                })
            },
            //搜索建议过滤方法
            createFilter(queryString) {
                return (empjobNos) => {
                    return (empjobNos.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1);
                };
            },
            //当选择某一项建议时，自动填充后面的Input框内容
            handleSelect(item) {
                this.getRequest("/personnel/ec/getEmpByJobNo/"+item.value).then(resp=>{
                    if(resp){
                        this.hr.jobNo = resp.jobNo;
                        this.hr.name = resp.name;
                        this.hr.email = resp.email;
                        this.hr.phone = resp.phone;
                        this.hr.telephone = resp.telephone;
                        this.hr.address = resp.address;
                        this.hr.department.id = resp.department.id;
                        this.hr.department.name = resp.department.name;
                    }
                })
            },
            deleteHr(hr){
                this.$confirm('此操作将永久删除【' + hr.name + '】用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.deleteRequest("/system/hr/" + hr.id).then(resp => {
                        if (resp) {
                           this.getHrs();
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            search(){
                this.getHrs();
            },
            //hr为当前选择的用户信息
            hidePop(hr){
                //定义一个变量获取hr里的角色
                let roles = [];
                //对象拷贝
                Object.assign(roles,hr.roles);
                let flag = false;
                //如果用户在下拉框内选择的角色数跟hr中的角色数不一致，则说明要执行更新操作
                if(roles.length != this.selectroles.length){
                    flag = true;
                }else{
                    //遍历hr中的角色，一一对比
                    for(let i=0;i<roles.length;i++){
                        let role = roles[i];
                        //hr的角色跟选择的角色做比较，如果相等，则从roles这个变量中删除改角色，再进行下一轮的比较
                        for (let j = 0;j<this.selectroles.length;j++){
                            let  sr = this.selectroles[j];
                            if(role.id == sr){
                                roles.splice(i,1);
                                //删除操作会导致数组的length发生改表，i对应做自减
                                i--;
                                break;
                            }
                        }
                    }
                    //如果对比结束，roles中还存在角色，则说明要执行更新操作
                    if(roles.length !=0){
                        flag = true;
                    }
                }
                if (flag) {
                    let url = '/system/hr/updatehrrole?hrid=' + hr.id;
                    this.selectroles.forEach(sr => {
                        url += '&rids=' + sr;
                    })
                    this.putRequest(url).then(resp => {
                        if (resp) {
                            this.getHrs();
                        }
                    })
                }


            },
            showPop(hr){
                this.getAllRoles();
                let roles = hr.roles;
                this.selectroles = [];
                roles.forEach(r=>{
                    this.selectroles.push(r.id);
                })
            },
            enabledChange(hr){
                delete hr.roles;
                this.putRequest("/system/hr/",hr).then(resp=>{
                    if(resp){
                        this.getHrs();
                    }
                })
            },
            getAllRoles(){
                this.getRequest("/system/hr/roles/").then(resp=>{
                    if(resp){
                        this.allroles = resp;
                    }
                })
            },
            getHrs(){
                this.getRequest("/system/hr/?keywords="+this.keywords).then(resp=>{
                    if(resp){
                        this.hrs = resp;
                    }
                })
            },
            showAddView(){
                this.dialogVisible = true;
            },
            handleClose(){
                this.hr = {
                    jobNo:null,
                    department:{
                        id:null,
                        name:''
                    },
                    name:null,
                    phone:null,
                    telephone:null,
                    email:null,
                    address:null,
                    username:null,
                    password:null,
                    checkPass:null,
                    enabled:1,
                    remark:null
                };
            },
        }
    }
</script>

<style>
    .hrrole span{
        margin-right: 5px;
        margin-top: 5px;
    }
    .userinfo div{
        font-size: 12px;
        color: black;
    }
    .userinfo{
        margin-top: 10px;
    }
    .imgposition{
        width: 100%;
        display: flex;
        justify-content: center;
    }
    .userface{
        width: 72px;
        height: 72px;
        border-radius: 72px;
    }
    .hrcenter{
        margin-top: 10px;
        display: flex;
        /*自动换行*/
        flex-wrap: wrap;
        justify-content: space-around;
    }
    .hrcard{
        width: 288px;
        margin-bottom: 18px;
    }
</style>
